const express = require("express");
const router = express.Router();
const User = require("../models/Users");
router.get("/test", (req, res) => {
  res.json({ msg: "login works" });
});
//注册接口
router.post("/register", async (req, res) => {
  try {
    //接收数据
    const { name, email, passWord, identity } = req.body;
    // 账号是否已经存在
    const count = await User.count({ email });
    if (count > 0) {
      res.sendJson("管理员账号已经存在！");
    } else {
      await User.insertOne({
        name: name,
        email: email,
        password: passWord,
        identity: identity,
      });
      res.sendJson("添加管理员成功", 1);
    }
  } catch (err) {
    console.log(err);
    res.sendJson("管理员添加失败", -1);
  }
});
// 登录接口
router.post("/login", async (req, res) => {
  const { email, password } = req.body;
  //根据email查询出信息
  const useInfo = await User.findEmal(email);
  if (useInfo && useInfo.password === password) {
    res.sendJson(useInfo.name, 1);
  } else {
    res.sendJson("没有查到相应用户", -1);
  }
});

module.exports = router;
